import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, DatePicker, Popover, Input, Card, Select, Alert, Spin, Popconfirm } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryOrgSettleListParams, OrgSettle } from './services';
import { OrgSettleStatus, getOrgWaitSettle, queryOrgSettleList, settleConfirm } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import Ellipsis from '@/components/Ellipsis';
import dayjs from 'dayjs';
import { enum2options } from '@/utils/enum2options';
import OrgSelect from '@/components/OrgSelect';
import { styled, history, Access } from '@umijs/max'
import { jump2target } from '@/utils/common';
import PersonSelect from '@/components/personSelect';

const StatisticCard = styled.div`
  width: 100%;
  height: 100px;
  background: #F7F8FA;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 40px;

  .content {
    width: 100%;
    display: flex;
    align-items: center;

    .title {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 14px;
      color: #222222;
    }

    .value {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: bold;
      font-size: 20px;
      color: #222222;
    }
  }
`

const dateFormat = (yyyymmdd: string) => {
  return `${yyyymmdd.substring(0, 4)}-${yyyymmdd.substring(4,6)}-${yyyymmdd.substring(6)}`
}

const OrgSettlePage: React.FC<RoutePageProps> = (props) => {
  const [searchForm] = Form.useForm<QueryOrgSettleListParams>()
  const [searchParams, setSearchParams] = useState<QueryOrgSettleListParams>({
    pageNum: 1, pageSize: 10,
    beginDay: dayjs().subtract(31, 'days').format('YYYY-MM-DD 00:00:00'),
    endDay: dayjs().format('YYYY-MM-DD 23:59:59'),
  })
  const list = useRequest(() => queryOrgSettleList(searchParams), {
    refreshDeps: [searchParams],
  })
  const waitSettle = useRequest(() => getOrgWaitSettle(searchParams), {
    refreshDeps: [searchParams]
  })
  const confirmReq = useRequest(settleConfirm, {manual: true})

  const onFinish = (formValues: any) => {
    let param = {
      ...searchParams,
      personId: formValues.org?.id,
      status: formValues.status,
      settleId: formValues.settleId,
      pageNum: 1,
    };
    if (formValues.timeRange && formValues.timeRange.length > 0) {
      param.beginDay = formValues.timeRange[0]?.format('YYYY-MM-DD 00:00:00');
      param.endDay = formValues.timeRange[1]?.format('YYYY-MM-DD 23:59:59');
    } else {
      param.beginDay = null;
      param.endDay = null;
    }
    setSearchParams(param)
  }

  const openDetail = (record: OrgSettle) => {
    sessionStorage.setItem('__orgSettle_data', JSON.stringify(record))
    jump2target(`/moneySettle/orgSettle/detail?sKey=__orgSettle_data___${new Date().getTime()}`, {needRefresh: true})
  }

  const columns: ColumnsType<OrgSettle> = [
    {
      title: '结算单ID',
      dataIndex: 'settleId',
      width: 100,
    },
    {
      title: '结算桩主',
      dataIndex: 'telephone',
      width: 180,
      render: val => <Popover content={val}><Ellipsis>{val}</Ellipsis></Popover>
    },
    {
      title: '结算周期',
      dataIndex: 'beginDay',
      width: 200,
      render: (val, record) => {
        if (!val) return '--'
        if (!record.endDay) return `${dateFormat(val)}至 --`
        return `${dateFormat(val)}至${dateFormat(record.endDay)}`
      }
    },
    {
      title: '结算电量(度)',
      dataIndex: 'power',
      width: 140,
      render: val => val?.toLocaleString() || '--'
    },
    {
      title: '结算充电费用(元)',
      key: 'settleMoney',
      width: 140,
      render: (val, record) => {
        const _total = parseFloat((record.chargeElectricMoney + record.chargeServiceMoney).toFixed(2))
        return _total.toLocaleString()
      }
    },

    {
      title: '流量费用(元)',
      key: 'networkFee',
      width: 140,
      render: (_, record) => {
        return record.networkFee?.toLocaleString() || '0.00'
      }
    },
    {
      title: '平台抽成(元)',
      dataIndex: 'platGetMoney',
      width: 140,
      render: platGetMoney => {
        return platGetMoney?.toLocaleString() || '0.00'
      }
    },
    {
      title: '城市经理人抽成(元)',
      dataIndex: 'cityGetMoney',
      width: 140,
      render: cityGetMoney => {
        return cityGetMoney?.toLocaleString() || '0.00'
      }
    },

    {
      title: '通道费(元)',
      dataIndex: 'pathMoney',
      width: 140,
      render: pathMoney => pathMoney?.toLocaleString() || '0.00'
    },
    {
      title: '结算费(元)',
      dataIndex: 'realMoney',
      width: 140,
      render: val => val?.toLocaleString()
    },
    // {
    //   title: '到账金额(元)',
    //   key: 'arriveMoney',
    //   width: 140,
    //   render: (val, record) => {
    //     const _total = parseFloat((record.chargeElectricMoney + record.chargeServiceMoney + record.occupyMoney).toFixed(2))
    //     const _invoice = parseFloat((record.chargeInvoiceMoney + record.occupyInvoiceMoney).toFixed(2))
    //     const _arrive = parseFloat((_total - _invoice - record.realMoney - (record.pathMoney || 0)).toFixed(2))
    //     return _arrive.toLocaleString()
    //   }
    // },
    {
      title: '付款状态',
      dataIndex: 'status',
      width: 140,
      render: val => val ? OrgSettleStatus[val] : '--'
    },
    {
      title: '提交时间',
      dataIndex: 'createTime',
      width: 140,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '操作',
      key: 'operation',
      width: 180,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <Access accessible={record.status === OrgSettleStatus.待打款 || record.status === OrgSettleStatus['待打款(已修改资料)']}>
            <Popconfirm
              title={`确认打款吗?`}
              onConfirm={() => confirmReq.runAsync({settleId: record.settleId, status: record.status}).then(list.refresh)}
              okText="确认"
              cancelText="取消"
            >
              <a>确认打款</a>
            </Popconfirm>
          </Access>
          <a onClick={() => openDetail(record)}>结算单详情</a>
        </Space>
      }
    },
  ]

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshOrgSettleList', refresh)
    return () => {
      window.removeEventListener('refreshOrgSettleList', refresh)
    }
  }, [])

  useEffect(() => {
    const { settleId } = props.params
    if (settleId) {
      searchForm.setFieldsValue({settleId})
      onFinish({settleId:settleId,timeRange: [dayjs().subtract(31, 'days'), dayjs()]});
    }
  }, [props.params.settleId])

  return (
    <div className='container'>
      <Card>
        <div className="search-card">
          <Form name='searchOrgSettleForm' form={searchForm} onFinish={onFinish} initialValues={{
            timeRange: [dayjs().subtract(31, 'days'), dayjs()]
          }}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='结算单ID' name='settleId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='付款状态' name='status'>
                  <Select placeholder='请选中' options={enum2options(OrgSettleStatus)} style={{width: '100%'}} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='私桩主' name='org'>
                  <PersonSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='结算时间' name='timeRange'>
                  <DatePicker.RangePicker allowClear={false} style={{width: '100%'}} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </Card>
      <Card title='结算提现记录'>
        {/*<Alert message="到账金额 =（充电结算金额+占位结算金额）- 扣款调整记录 + 返款调整记录" type="info" showIcon />*/}
        <Spin spinning={waitSettle.loading}>
          <Row gutter={24} style={{margin: '20px 0'}}>
            <Col span={6}>
              <StatisticCard>
                <div className="content">
                  <div className="title">充电待结算金额（元）：</div>
                  <div className="value">{waitSettle.data?.data.chargeMoney?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
            <Col span={6}>
              <StatisticCard style={{background: '#FFF8F8'}}>
                <div className="content">
                  <div className="title">占用待结算金额（元）：</div>
                  <div className="value">{waitSettle.data?.data.occupyMoney?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
          </Row>
        </Spin>
        <Table<OrgSettle>
          rowKey='settleId'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </Card>
    </div>
  );
};

export default OrgSettlePage;
